package org.jamin.lending.service.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jamin.lending.domain.entity.*;
import org.jamin.lending.domain.form.manger.SMSConfigForm;
import org.jamin.lending.domain.form.manger.SMSLogForm;
import org.jamin.lending.domain.form.manger.TemplateForm;
import org.jamin.lending.repository.ConfigRepository;
import org.jamin.lending.repository.SMSLogRepository;
import org.jamin.lending.repository.TemplateRepository;
import org.jamin.lending.service.MessageService;
import org.jamin.lending.tool.AlidayuAchieve;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 黄文杰
 */
@Service
@Transactional
public class MessageServiceImpl implements MessageService {

    private Log log = LogFactory.getLog(getClass());

    @Autowired
    private TemplateRepository templateRepository;

    @Autowired
    private SMSLogRepository smsLogRepository;

    @Autowired
    private ConfigRepository configRepository;

    @Override
    public void sendManagerMessage(Auser auser, String message) {

    }

    @Override
    public Page<Template> findTemplate(TemplateForm templateForm) {
        Pageable pageable = new PageRequest(templateForm.getPageCurrent(), templateForm.getPageSize());
        return this.templateRepository.findAll(pageable);
    }

    @Override
    public void initMessageTemplate(String pathname) throws Exception {
        log.info("默认模板配置路径:" + pathname);
        File file = new File(pathname);
        List<Template> templates = new ArrayList<Template>();
        JsonNode jsonNode = new ObjectMapper().readTree(file);
        log.info("配置数据加载成功，正在装备数据中");
        for (int i = 0; i < jsonNode.size(); i++) {
            String json = jsonNode.get(i).toString();
            Template template = new ObjectMapper().readValue(json, Template.class);
            templates.add(template);
        }
        this.templateRepository.save(templates);
    }

    @Override
    public Template getTemplateOne(String code) {
        return this.templateRepository.findOne(code);
    }

    @Override
    public void saveTemplate(Template template) {
        this.templateRepository.save(template);
    }

    @Override
    public Page<SMSLog> findSMSLogList(final SMSLogForm smsLogForm) {
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        Pageable pageable = new PageRequest(smsLogForm.getPageCurrent(),smsLogForm.getPageSize(), sort);
        Specification<SMSLog> specification = new Specification<SMSLog>() {
            @Override
            public Predicate toPredicate(Root<SMSLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if(smsLogForm.getPhone() != null){
                    predicates.add(cb.like(root.get("phone").as(String.class),"%"+smsLogForm.getPhone()+"%"));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return query.where(predicates.toArray(predicates1)).getRestriction();
            }
        };
        return this.smsLogRepository.findAll(specification,pageable);
    }

    public void readySMS(String content,String phone) throws IOException {
        Config config = this.configRepository.findOne("SMS_config");
        SMSConfigForm smsConfigForm = new ObjectMapper().readValue(config.getContent(),SMSConfigForm.class);
        switch (smsConfigForm.getSmsSuppliers()){
            case alidayu:
                AlidayuAchieve alidayuAchieve = new AlidayuAchieve(smsConfigForm.getAppKey(),null);
                alidayuAchieve.sendSms();
                break;

        }
        SMSLog smsLog = new SMSLog();
        smsLog.setContent(content);
        smsLog.setPhone(phone);
        smsLog.setSendTime(new Timestamp(System.currentTimeMillis()));
        this.smsLogRepository.save(smsLog);
    }

}
